package com.zou.jokes.adapter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ProgressBarDrawable;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.zou.jokes.Constant;
import com.zou.jokes.R;
import com.zou.jokes.beans.BaseDataEntity;
import com.zou.jokes.sqlite.MyDao;
import com.zou.jokes.utils.FileUtil;
import com.zou.jokes.utils.RxBus;
import com.zou.jokes.utils.ToastUtil;
import com.zou.jokes.utils.UserEvent;

import java.io.File;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zou on 2016/6/3.
 */
public class FavoriteAdapter extends RecyclerView.Adapter implements View.OnClickListener {

    private static final int TIME  = 0;
    private static final int PICS  = 1;
    private static final int JOKES = 2;
    private final List<BaseDataEntity> datas;
    ClipboardManager clipboardManager;
    Context          context;
    private final GenericDraweeHierarchyBuilder builder;
    private final MyDao                         myDao;

    public FavoriteAdapter(List<BaseDataEntity> datas, Context context) {
        this.datas = datas;
        this.context = context;
        this.clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        myDao = new MyDao(context);
        builder = new GenericDraweeHierarchyBuilder(context.getResources());
    }

    @Override

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case JOKES:
                return new JokesHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_jokes, parent, false));
            case PICS:
                return new PicsHolder(LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_pics, parent, false));
            default:
                return null;

        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof JokesHolder) {
            ((JokesHolder) holder).btn_copy_content.setTag(position);
            ((JokesHolder) holder).btn_copy_content.setOnClickListener(this);
            ((JokesHolder) holder).btn_share_joke.setTag(position);
            ((JokesHolder) holder).btn_share_joke.setOnClickListener(this);
            ((JokesHolder) holder).btn_like_joke.setTag(position);
            ((JokesHolder) holder).btn_like_joke.setOnClickListener(this);

            ((JokesHolder) holder).joke_content.setText(datas.get(position).getContent());
            ((JokesHolder) holder).update_time.setText(datas.get(position).getUpdatetime());

/*            if (myDao.queryExists(datas.get(position - 1).getHashId())) {
                ((JokesHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
            }*/

            Observable.just(myDao.queryExists(datas.get(position).getHashId()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            ((JokesHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
                        }
                    });
        } else if (holder instanceof PicsHolder) {

            ((PicsHolder) holder).btn_copy_content.setTag(position);
            ((PicsHolder) holder).btn_copy_content.setOnClickListener(this);
            ((PicsHolder) holder).btn_share_joke.setTag(position);
            ((PicsHolder) holder).btn_share_joke.setOnClickListener(this);
            ((PicsHolder) holder).btn_like_joke.setTag(position);
            ((PicsHolder) holder).btn_like_joke.setOnClickListener(this);

            ((PicsHolder) holder).joke_content.setText(datas.get(position).getContent());
            ((PicsHolder) holder).update_time.setText(datas.get(position).getUpdatetime());

/*
            ViewTreeObserver vto = ((PicsHolder) holder).draweeView.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(() -> width = ((PicsHolder) holder).draweeView.getWidth());
*/
            ((PicsHolder) holder).draweeView.setAspectRatio(3f);

            GenericDraweeHierarchy hierarchy = builder.setFadeDuration(300)
                    .setProgressBarImage(new ProgressBarDrawable())
                    .setPlaceholderImage(context.getResources().getDrawable(R.drawable.ic_insert_emoticon_yellow_24dp))
                    .setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY)
                    .build();
            ((PicsHolder) holder).draweeView.setHierarchy(hierarchy);
            Log.e("wocao", "onBindViewHolder: " + datas.get(position).getUrl());
//            ((PicsHolder) holder).draweeView.setImageURI(Uri.parse(datas.get(position - 1).getUrl()));\
            ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                    if (imageInfo == null) {
                        return;
                    }
                    int x = imageInfo.getWidth();
                    int y = imageInfo.getHeight();
                    Log.e("wocao", "onFinalImageSet: " + "x=" + x + " y=" + y);
                    ((PicsHolder) holder).draweeView.setAspectRatio((float) x / y);
                    Log.e("wocao", ((PicsHolder) holder).draweeView.getAspectRatio() + "ratio");

                }
            };


            DraweeController controller = Fresco.newDraweeControllerBuilder().setAutoPlayAnimations(true)
                    .setUri(Uri.parse(datas.get(position).getUrl()))
                    .setControllerListener(controllerListener)
                    .build();
            ((PicsHolder) holder).draweeView.setController(controller);

/*            if (myDao.queryExists(datas.get(position - 1).getHashId())) {
                ((PicsHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
            }*/


            Observable.just(myDao.queryExists(datas.get(position).getHashId()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            ((PicsHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_black_24dp);
                        } else {
                            ((PicsHolder) holder).btn_like_joke.setImageResource(R.drawable.ic_favorite_border_black_24dp);
                        }
                    });
        }
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }


    @Override
    public int getItemViewType(int position) {
        if (TextUtils.isEmpty(datas.get(position).getUrl())) {
            return JOKES;
        } else {
            return PICS;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_copy_content:
                if (TextUtils.isEmpty(datas.get((Integer) v.getTag()).getUrl())) {
                    clipboardManager.setPrimaryClip(ClipData.newPlainText("joke", datas.get((Integer) v.getTag()).getContent()));
                    ToastUtil.showToast(context, "已复制");
                    Log.e("wocao", "onClick: " + clipboardManager.getPrimaryClip());
                } else {
                    clipboardManager.setPrimaryClip(ClipData.newPlainText("joke", datas.get((Integer) v.getTag()).getUrl()));
                    ToastUtil.showToast(context, "已复制图片链接");
                    Log.e("wocao", "onClick: " + clipboardManager.getPrimaryClip());
                }

                break;

            case R.id.btn_share_joke:

                if (TextUtils.isEmpty(datas.get((Integer) v.getTag()).getUrl())) {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_SUBJECT, "分享欢乐");
                    intent.putExtra(Intent.EXTRA_TEXT, datas.get((Integer) v.getTag()).getContent());
                    context.startActivity(Intent.createChooser(intent, "分享欢乐"));
                } else {

                    String   url      = datas.get((Integer) v.getTag()).getUrl();
                    String[] split    = url.split("/");
                    String   fileName = split[split.length - 1];
                    FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory()
                            .getMainFileCache().getResource(new SimpleCacheKey(datas.get((Integer) v.getTag()).getUrl()));
                    File file = resource.getFile();
                    Log.e("wocao", "fresco cache: " + file.getAbsolutePath());
                    Log.e("wocao", "filename: " + fileName);

                    File localFile = new File(context.getExternalFilesDir(null), fileName);

                    FileUtil.copyfile(file, localFile);

                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("image/*");
                    intent.putExtra(Intent.EXTRA_SUBJECT, "分享趣图");
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(localFile));
                    context.startActivity(Intent.createChooser(intent, "分享趣图"));
                }

                break;
            case R.id.btn_like_joke:
                Observable.just(myDao.queryExists(datas.get((Integer) v.getTag()).getHashId()))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aBoolean -> {
                            if (!aBoolean) {
                                Observable.just(myDao.addDate(System.currentTimeMillis()
                                        , datas.get((Integer) v.getTag()).getContent()
                                        , datas.get((Integer) v.getTag()).getHashId()
                                        , datas.get((Integer) v.getTag()).getUnixtime()
                                        , datas.get((Integer) v.getTag()).getUpdatetime()
                                        , datas.get((Integer) v.getTag()).getUrl()
                                ))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(aLong -> {
                                            if (aLong != -1) {
                                                ((ImageView) v).setImageResource(R.drawable.ic_favorite_black_24dp);
                                                ToastUtil.showToast(context, "已收藏");
                                                this.notifyDataSetChanged();
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEJOKE, ""));
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEPIC, ""));
                                            }
                                        });
                            } else {
                                Observable.just(myDao.deleteDate(datas.get((Integer) v.getTag()).getHashId()
                                ))
                                        .subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(integer -> {

                                            if (integer == 1) {
                                                ((ImageView) v).setImageResource(R.drawable.ic_favorite_border_black_24dp);
                                                ToastUtil.showToast(context, "已取消收藏");
                                                datas.remove((int) v.getTag());
                                                notifyItemRemoved((Integer) v.getTag());
                                                reload();
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEJOKE, ""));
                                                RxBus.getDefault().post(new UserEvent(Constant.UPDATEPIC, ""));
                                            }

                                        });
                            }
                        });


        }
    }

    private void reload() {
        Observable.just(myDao.getDatas())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(baseDataEntities -> {
                    datas.clear();
                    datas.addAll(baseDataEntities);
                    notifyItemRangeChanged(0, datas.size());
                });
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);

    }

    class JokesHolder extends RecyclerView.ViewHolder {
        TextView    joke_content;
        TextView    update_time;
        ImageButton btn_copy_content;
        ImageButton btn_share_joke;
        ImageButton btn_like_joke;

        public JokesHolder(View itemView) {
            super(itemView);
            joke_content = (TextView) itemView.findViewById(R.id.joke_content);
            update_time = (TextView) itemView.findViewById(R.id.update_time);
            btn_copy_content = (ImageButton) itemView.findViewById(R.id.btn_copy_content);
            btn_share_joke = (ImageButton) itemView.findViewById(R.id.btn_share_joke);
            btn_like_joke = (ImageButton) itemView.findViewById(R.id.btn_like_joke);
        }
    }

    class PicsHolder extends RecyclerView.ViewHolder {
        TextView         joke_content;
        TextView         update_time;
        ImageButton      btn_copy_content;
        ImageButton      btn_share_joke;
        ImageButton      btn_like_joke;
        SimpleDraweeView draweeView;


        public PicsHolder(View itemView) {
            super(itemView);
            joke_content = (TextView) itemView.findViewById(R.id.joke_content);
            update_time = (TextView) itemView.findViewById(R.id.update_time);
            btn_copy_content = (ImageButton) itemView.findViewById(R.id.btn_copy_content);
            btn_share_joke = (ImageButton) itemView.findViewById(R.id.btn_share_joke);
            btn_like_joke = (ImageButton) itemView.findViewById(R.id.btn_like_joke);
            draweeView = (SimpleDraweeView) itemView.findViewById(R.id.drawee);
        }
    }


}
